package com.atguigu.weixin.msg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import com.alibaba.fastjson.JSON;
import com.atguigu.weixin.json.TemplateMsg;
import com.atguigu.weixin.kit.DuplicateMessageKit;
import com.atguigu.weixin.kit.MessageCreateKit;
import com.atguigu.weixin.kit.WeixinEventKit;
import com.atguigu.weixin.kit.WeixinKit;
import com.atguigu.weixin.model.WeixinContext;
import com.atguigu.weixin.model.WeixinFianlValue;
import com.atguigu.weixin.quartz.RefreshAccessTokenTask;

/**
 * 消息返回处理类
 * @author Administrator
 *
 */
public class MessageKit {
	
	private static Map<String,String> replyMsgs=new HashMap<String,String>();
	static{
		replyMsgs.put("123", "你输入了123");
		replyMsgs.put("hello", "world");
		replyMsgs.put("run", "祝你一路平安!");
	 }
	/**
	 * 将xml转成map对象
	 * @param req
	 * @return
	 * @throws IOException 
	 * @throws DocumentException 
	 */
 @SuppressWarnings("unchecked")
public static Map<String,String> reqMsg2Map(HttpServletRequest req) throws IOException{
	  try {
		String xml=req2xml(req);
		  Map<String,String> maps=new HashMap<String,String>();
		  Document document=DocumentHelper.parseText(xml);
		  Element root=document.getRootElement();
		  List<Element> eles=root.elements();
		  for (Element e : eles) {
			  maps.put(e.getName(), e.getTextTrim());
		 }
		  return maps;
	} catch (DocumentException e) {
		e.printStackTrace();
	}
	  return null;
	  
  }
  
  //转成xml
  public static String req2xml(HttpServletRequest req) throws IOException{
	  BufferedReader br=null;
	  br=new BufferedReader(new InputStreamReader(req.getInputStream(),"UTF-8"));
	  String str=null;
	  StringBuffer sb=new StringBuffer();
	  while((str=br.readLine())!=null){
		   sb.append(str);
	  }
	  return sb.toString();
	  
  }
//响应消息的类型
public static String handlerMag(Map<String, String> msgMap) throws IOException {
	System.out.println("%%%%%%%%%%%%%%%%:"+msgMap);
	if(!DuplicateMessageKit.checkDuplicate(msgMap)){//如果不存在 响应的消息去  排重（去掉重复的）
		String rel = DuplicateMessageKit.getRel(msgMap);
		return rel;
	}
	String msgType=msgMap.get("MsgType");
	if(msgType.trim().equals(WeixinFianlValue.MSG_EVENT_TYPE)){//如果是事件
		String rel=WeixinEventKit.handlerEventMsg(msgMap);
		DuplicateMessageKit.setRel(msgMap, rel);
		return rel;
	}else if(msgType.equals(WeixinFianlValue.MSG_TEXT_TYPE)){//如果是文本
		return textTypeHandler(msgMap);
	}else if(msgType.equals(WeixinFianlValue.MSG_IMAGE_TYPE)){//如果图片
		//第二个参数是图片的mediaId
		return imageTypeHandler(msgMap,"-wSclmh4ibDHX9n1udW2bdHIyBkaCgQ5YEhg8jL56SB_1Ym80uA7IJCKXpL-qN4P");
	}
	else {
		return textTypeHandler(msgMap);
	}
}


private static String hanlderCommonMsg(Map<String, String> msgMap) throws IOException {
	
	return map2xml( MessageCreateKit.createTextMsg(msgMap, "我收到了消息"));
}


//如果接收的图片返回图片xml格式微信识别的信息
private static String imageTypeHandler(Map<String, String> msgMap, String mediaId) throws IOException {
	 Map<String,Object> map=new HashMap<String,Object>();
	    map.put("ToUserName",msgMap.get("FromUserName"));
	    map.put("FromUserName", msgMap.get("ToUserName"));
	    map.put("CreateTime",new Date().getTime()+"");
	    map.put("MsgType","image");
	    map.put("Image", "<MediaId>"+mediaId+"</MediaId>");
	 return map2xml(map);
}

//根据接收的信息 转成返回微信消息xml格式的信息   hanlderCommonMsg
private static String textTypeHandler(Map<String, String> msgMap) throws IOException {
  Map<String,Object> map=new HashMap<String,Object>();
    map.put("ToUserName",msgMap.get("FromUserName"));
    map.put("FromUserName", msgMap.get("ToUserName"));
    map.put("CreateTime",new Date().getTime()+"");
    map.put("MsgType","text");
    String replyContent="你请求的消息的内容不正确";
    String con=msgMap.get("Content");
    if(replyMsgs.containsKey(con)){
    	replyContent=replyMsgs.get(con);
    }
    
    map.put("Content",replyContent);
    
    
	return map2xml(map);
}

/**
 * map 转成xml
 * @param map
 * @return
 * @throws IOException
 */
public static String map2xml(Map<String, Object> map) throws IOException {
	Document d = DocumentHelper.createDocument();
	Element root = d.addElement("xml");
	Set<String> keys = map.keySet();
	for(String key:keys) {
		Object o = map.get(key);
		if(o instanceof String) {
			String t = (String)o;
//			System.out.println(t);
			if(t.indexOf("<a")>=0) {
				root.addElement(key).addCDATA(t); 
			} else {
				root.addElement(key).addText((String)o);
			}
		} else {
			
		}
		
	}
	StringWriter sw = new StringWriter();
	XMLWriter xw = new XMLWriter(sw);
	xw.setEscapeText(false);
	xw.write(d);
	return sw.toString();
}


//发送模板消息
@SuppressWarnings("null")
public static String postTemplateMsg(TemplateMsg tm){
	CloseableHttpClient client=null;
	CloseableHttpResponse resp=null;
    try {
    	client=HttpClients.createDefault();
		String url=WeixinFianlValue.SEND_TEMPLATE_MSG;
		System.out.println("@@@@@"+WeixinContext.getAccessToken());
		url=url.replace("ACCESS_TOKEN",WeixinContext.getAccessToken());
		HttpPost post=new HttpPost(url);
		String json=JSON.toJSONString(tm);
		post.addHeader("Content-Type","application/json");
		StringEntity entity=new StringEntity(json, ContentType.create("application/json","UTF-8"));
		post.setEntity(entity);
		resp=client.execute(post);
		int statusCode=resp.getStatusLine().getStatusCode();
		if(statusCode>=200&&statusCode<300){
			String str=EntityUtils.toString(resp.getEntity());
			System.out.println(str);
			return str;
		}
	} catch (UnsupportedCharsetException e) {
		e.printStackTrace();
	} catch (ClientProtocolException e) {
		e.printStackTrace();
	} catch (ParseException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}finally{
		try {
			if(client!=null) client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			if(resp!=null) resp.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    return null;
}


//模板消息发送
public static String postTemplateMsggroup(TemplateMsg tm){
		String url=WeixinFianlValue.SEND_TEMPLATE_MSG;
		url=url.replace("ACCESS_TOKEN",WeixinContext.getAccessToken());
		HttpPost post=new HttpPost(url);
		String json=JSON.toJSONString(tm);
		post.addHeader("Content-Type","application/json");
    return WeixinKit.postReq(url, json, "application/json");

}


}
